import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../theme/app_theme.dart';
import '../services/data_service.dart';
import '../models/period_model.dart'; // 包含UserProfile类

class ProfileCompletionScreen extends StatefulWidget {
  const ProfileCompletionScreen({super.key});

  @override
  ProfileCompletionScreenState createState() => ProfileCompletionScreenState();
}

class ProfileCompletionScreenState extends State<ProfileCompletionScreen> {
  DateTime _selectedDate = DateTime.now();
  DateTime _currentMonth = DateTime.now();
  bool _hasSelectedDate = false;
  List<dynamic> _userRecords = []; 

  int _cycleLength = 28; 

  int _periodLength = 5; 

  final bool _isSubmitting = false; 

  String? _errorMessage; 

  
  
  

  @override
  void initState() {
    super.initState();
    _loadUserData();
  }
  
  Future<void> _loadUserData() async {
    try {
      
      
      setState(() {
        _userRecords = [];
      });
    } catch (e) {
      
      setState(() {
        _userRecords = [];
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      
      body: SafeArea(
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.only(top: 20.0, bottom: 20.0),
              decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Color.fromRGBO(255, 243, 248, 1),
                          Color.fromRGBO(255, 255, 255, 1),
                        ],
                      ),
                    ),
              child: const Column(
                children: [
                  Text(
                    '完善资料',
                    style: TextStyle(
                      fontSize: 24.0,
                      fontWeight: FontWeight.bold,
                      color: Colors.black,
                    ),
                  ),
                  SizedBox(height: 8.0),
                  Text(
                    '请点击最近一次经期开始日',
                    style: TextStyle(
                      fontSize: 16.0,
                      color: Colors.black,
                    ),
                  ),
                  SizedBox(height: 4.0),
                  Text(
                    '经期信息将用于经期记录、分析及预测',
                    style: TextStyle(
                      fontSize: 14.0,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  children: [
                    _buildCalendar(),
                    const SizedBox(height: 20.0),
                    _buildCycleSettings(),
                    const SizedBox(height: 20.0),
                    _hasSelectedDate
                        ? ElevatedButton(
                            onPressed: _isSubmitting ? null : () {
                              
                              _markFirstLaunchComplete(context);
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: AppTheme.primaryColor,
                              minimumSize: const Size.fromHeight(48.0),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(24.0),
                              ),
                            ),
                            child: _isSubmitting
                                ? const SizedBox(
                                    width: 20.0,
                                    height: 20.0,
                                    child: CircularProgressIndicator(
                                      strokeWidth: 2.0,
                                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                                    ),
                                  )
                                : const Text(
                                    '继续',
                                    style: TextStyle(
                                      fontSize: 16.0,
                                      color: Colors.white,
                                    ),
                                  ),
                          )
                        : const SizedBox.shrink(),
                    const SizedBox(height: 20.0),
                    if (_errorMessage != null)
                      Container(
                        padding: const EdgeInsets.all(12.0),
                        margin: const EdgeInsets.only(bottom: 16.0),
                        decoration: BoxDecoration(
                          color: Colors.red[50],
                          borderRadius: BorderRadius.circular(8.0),
                          border: Border.all(color: Colors.red[200]!),
                        ),
                        child: Row(
                          children: [
                            Icon(Icons.error_outline, color: Colors.red[600], size: 20.0),
                            const SizedBox(width: 8.0),
                            Expanded(
                              child: Text(
                                _errorMessage!,
                                style: TextStyle(
                                  color: Colors.red[700],
                                  fontSize: 14.0,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    TextButton(
                      onPressed: _isSubmitting ? null : () async {
                        try {
                          // 标记首次启动完成，即使没有输入信息
                          final prefs = await SharedPreferences.getInstance();
                          await prefs.setBool('isFirstLaunch', false);
                          
                          if (context.mounted) {
                            Navigator.pushReplacementNamed(context, '/main');
                          }
                        } catch (e) {
                          debugPrint('设置首次启动状态失败: $e');
                          if (context.mounted) {
                            Navigator.pushReplacementNamed(context, '/main');
                          }
                        }
                      },
                      child: const Text(
                        '我忘了，继续',
                        style: TextStyle(
                          fontSize: 14.0,
                          color: AppTheme.primaryColor,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCalendar() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.0),
        boxShadow: const [
          BoxShadow(
            color: Colors.grey,
            spreadRadius: 1,
            blurRadius: 3,
            offset: Offset(0, 2),
          ),
        ],
      ),
      padding: const EdgeInsets.all(20.0),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              IconButton(
                icon: const Icon(Icons.arrow_back_ios),
                onPressed: () {
                  setState(() {
                    _currentMonth = DateTime(
                      _currentMonth.year,
                      _currentMonth.month - 1,
                    );
                  });
                },
              ),
              Text(
                '${_currentMonth.year}年${_currentMonth.month}月',
                style: const TextStyle(
                  fontSize: 16.0,
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                ),
              ),
              IconButton(
                icon: const Icon(Icons.arrow_forward_ios),
                onPressed: () {
                  setState(() {
                    _currentMonth = DateTime(
                      _currentMonth.year,
                      _currentMonth.month + 1,
                    );
                  });
                },
              ),
            ],
          ),
          const SizedBox(height: 16.0),
          _buildCalendarDays(),
        ],
      ),
    );
  }

  Widget _buildCalendarDays() {
    List<Widget> dayWidgets = [];
    
    
    List<String> weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    for (String weekday in weekdays) {
      dayWidgets.add(
        Expanded(
          child: Center(
            child: Text(
              weekday,
              style: const TextStyle(
                fontSize: 14.0,
                fontWeight: FontWeight.w500,
                color: Colors.grey,
              ),
            ),
          ),
        ),
      );
    }
    
    
    DateTime firstDayOfMonth = DateTime(_currentMonth.year, _currentMonth.month, 1);
    
    DateTime lastDayOfMonth = DateTime(_currentMonth.year, _currentMonth.month + 1, 0);
    
    
    int firstDayWeekday = firstDayOfMonth.weekday;
    for (int i = 0; i < firstDayWeekday; i++) {
      dayWidgets.add(const Expanded(child: SizedBox.shrink()));
    }
    
    
    for (int day = 1; day <= lastDayOfMonth.day; day++) {
      DateTime date = DateTime(_currentMonth.year, _currentMonth.month, day);
      bool isToday = date.year == DateTime.now().year &&
          date.month == DateTime.now().month &&
          date.day == DateTime.now().day;
      bool isSelected = _selectedDate.year == date.year &&
          _selectedDate.month == date.month &&
          _selectedDate.day == date.day;
      
      bool isRecentPeriod = false;
      
      if (_userRecords.isNotEmpty) {
        isRecentPeriod = _userRecords.any((record) => record.date == date && record.isPeriod);
      }
      
      Color? bgColor;
      
      if (isSelected) {
        bgColor = AppTheme.primaryColor;
      } else if (isRecentPeriod) {
        bgColor = const Color.fromRGBO(255, 221, 235, 1);
      }
      
      dayWidgets.add(
        Expanded(
          child: GestureDetector(
            onTap: () {
              setState(() {
                _selectedDate = date;
                _hasSelectedDate = true;
              });
            },
            child: Container(
              height: 40.0,
              margin: const EdgeInsets.all(4.0),
              decoration: bgColor != null
                  ? BoxDecoration(
                      color: bgColor,
                      borderRadius: BorderRadius.circular(20.0),
                    )
                  : null,
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      '$day',
                      style: const TextStyle(
                        fontSize: 14.0,
                        fontWeight: FontWeight.bold,
                        color: Colors.black,
                      ),
                    ),
                    if (isToday && !isSelected) 
                      Text(
                        '今天',
                        style: TextStyle(
                          fontSize: 10.0,
                          color: Colors.grey[600],
                        ),
                      ),
                  ],
                ),
              ),
            ),
          ),
        ),
      );
    }
    
    return Column(
      children: [
        
        Row(children: dayWidgets.sublist(0, 7)),
        
        Column(
          children: [
            for (int i = 0; i < (dayWidgets.length - 7 + 6) ~/ 7; i++)
              Row(
                children: dayWidgets.sublist(
                  7 + i * 7,
                  7 + (i + 1) * 7 > dayWidgets.length
                      ? dayWidgets.length
                      : 7 + (i + 1) * 7,
                ),
              ),
          ],
        ),
      ],
    );
  }

  Future<void> _markFirstLaunchComplete(BuildContext context) async {
    if (!_hasSelectedDate) return;

    try {
      
      final userProfile = UserProfile(
        name: '用户', 
        birthDate: DateTime.now().subtract(const Duration(days: 25 * 365)), 
        height: 165, 
        weight: 55, 
        bloodType: 'A', 
        lastPeriodDate: _selectedDate,
        cycleLength: _cycleLength,
        periodLength: _periodLength,
        currentMode: 'period', 
        notificationsEnabled: true,
        darkMode: false,
        healthConditions: const [],
        isUsingBirthControl: false,
      );

      
      final dataService = DataService();
      await dataService.saveUserProfile(userProfile);
      debugPrint('User profile saved successfully');

      
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool('isFirstLaunch', false);
      debugPrint('First launch marked as complete');
      
      
      if (context.mounted) {
        // 直接跳转到主屏幕，而不是根路由
        Navigator.pushReplacementNamed(context, '/main');
      }
    } catch (e) {
      final errorDetails = e.toString();
      debugPrint('Failed to mark first launch complete: $errorDetails');
      // 显示更详细的错误消息
      if (context.mounted) {
        setState(() {
          _errorMessage = '保存用户资料失败：$errorDetails';
        });
      }
    }
  }
  
  Widget _buildCycleSettings() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.0),
        boxShadow: const [
          BoxShadow(
            color: Colors.grey,
            spreadRadius: 1,
            blurRadius: 3,
            offset: Offset(0, 2),
          ),
        ],
      ),
      padding: const EdgeInsets.all(20.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '经期设置',
            style: TextStyle(
              fontSize: 18.0,
              fontWeight: FontWeight.bold,
              color: Colors.black,
            ),
          ),
          const SizedBox(height: 16.0),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '经期周期（天）',
                style: TextStyle(fontSize: 16.0, color: Colors.black),
              ),
              Row(
                children: [
                  IconButton(
                    icon: const Icon(Icons.remove_circle_outline),
                    onPressed: () {
                      setState(() {
                        if (_cycleLength > 21) _cycleLength--;
                      });
                    },
                  ),
                  Text(
                    '$_cycleLength',
                    style: const TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
                  ),
                  IconButton(
                    icon: const Icon(Icons.add_circle_outline),
                    onPressed: () {
                      setState(() {
                        if (_cycleLength < 35) _cycleLength++;
                      });
                    },
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 16.0),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '经期持续时间（天）',
                style: TextStyle(fontSize: 16.0, color: Colors.black),
              ),
              Row(
                children: [
                  IconButton(
                    icon: const Icon(Icons.remove_circle_outline),
                    onPressed: () {
                      setState(() {
                        if (_periodLength > 3) _periodLength--;
                      });
                    },
                  ),
                  Text(
                    '$_periodLength',
                    style: const TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
                  ),
                  IconButton(
                    icon: const Icon(Icons.add_circle_outline),
                    onPressed: () {
                      setState(() {
                        if (_periodLength < 10) _periodLength++;
                      });
                    },
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 8.0),
          const Text(
            '提示：经期周期指两次月经第一天的间隔时间，通常为21-35天',
            style: TextStyle(fontSize: 12.0, color: Colors.grey),
          ),
        ],
      ),
    );
  }
}